package com.sxran.im.handler;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sxran.im.bean.MessageReqBody;
import com.sxran.im.controller.ImController;
import com.sxran.im.dao.ImGroupMapper;
import com.sxran.im.dao.ImUserGroupMapper;
import com.sxran.im.dao.ImUserMapper;
import com.sxran.im.info.ImConversation;
import com.sxran.im.info.ImGroup;
import com.sxran.im.info.ImUser;
import com.sxran.im.info.ImUserGroup;
import com.sxran.im.service.UserGroupService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class GetGroupInfoCmdHandler extends AbstractCmdHandler<ImGroup>{
    @Resource
    private ImGroupMapper imGroupMapper;
    @Resource
    private ImUserMapper imUserMapper;
    @Resource
    private ImUserGroupMapper imUserGroupMapper;

    @Override
    public Object doBeanService(ImGroup json) {
        String groupId = json.getGroupId();
        String curUserId = ImController.getCurUserId();
        ImGroup imGroup = imGroupMapper.selectById(groupId);
        Map<String, Object> objectMap = BeanUtil.beanToMap(imGroup);
        objectMap.put("isAdmin",false);
        // 获取群聊的用户组信息。
        LambdaQueryWrapper<ImUserGroup> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ImUserGroup::getGid,groupId);
        List<ImUserGroup> imUserGroups = imUserGroupMapper.selectList(queryWrapper);
        int size = imUserGroups.size();
        //
        List<Map<String, Object>> memberList = new ArrayList<>(size);
        for (int i = 0; i < size; i++) {
            ImUserGroup imUserGroup = imUserGroups.get(i);
            String uid = imUserGroup.getUid();
            ImUser imUser = imUserMapper.selectById(uid);
            Map<String, Object> userMap = BeanUtil.beanToMap(imUser);
            String role = imUserGroup.getRole();
            userMap.put("role", role);
            // 当前用户是不是管理员逻辑。
            if (curUserId.equals(uid) && "admin".equals(role) ) {
                objectMap.put("isAdmin",true);
            }
            //
            memberList.add(userMap);
        }
        //
        objectMap.put("memberList",memberList);
        return objectMap;
    }
}
